#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2024/12/13 23:25
# @Author  : 唐松
# @File    : config.py
# @Software: PyCharm

import yaml
from configs.setting import get_object_path
from util_tools.logger_util import logs


def read_config_file(one_node, two_node):
    """
    # 用于读取config.yaml文件 ，configs.yaml文件用于存储项目的配置信息
    :param one_node: 第一个key
    :param two_node: 第二个key
    :return:
    """
    try:
        with open(get_object_path() + "/configs/config.yaml", encoding="utf-8") as f:
            value = yaml.load(stream=f, Loader=yaml.FullLoader)
            return value[one_node][two_node]
    except Exception as e:
        logs.error(f'读取config.yaml文件, 失败原因: {e}')


def read_extract_yaml(node_name, sub_node_name=None):
    """
    用于读取extract.yaml文件，extract.yaml文件用于存储抽取的数据,用于数据的传递(跨页面.接口关联)
    :param node_name: 第一级key值
    :param sub_node_name: 下级key值
    :return:
    """

    try:
        with open(get_object_path() + "/configs/extract.yaml", encoding="utf-8") as f:
            extract_data = yaml.load(stream=f, Loader=yaml.FullLoader)
            if sub_node_name is None:
                return extract_data[node_name]
            else:
                return extract_data.get(node_name, {}).get(sub_node_name)

    except yaml.YAMLError as e:
        logs.error(f'读取read_extract_file失败，请检查格式。 {e}')
    except Exception as e:
        logs.error(f'Error: 未知异常 - {e}')


def write_extract_yaml(data):
    """
    写入到extract.yaml文件
    :param data: 写入的数据，必须为字典类型(dict)
    :return:
    """
    try:
        with open(get_object_path() + "/configs/extract.yaml", encoding="utf-8", mode='a') as f:
            if isinstance(data, dict):  # 如果是字典类型，就写入
                yaml.dump(data=data, stream=f, allow_unicode=True, sort_keys=False)
            else:
                logs.error('写入的数据必须为字典类型')
    except Exception as e:
        logs.error(f'写入extract.yaml失败, 失败原因: {e}')

# 用于清空extract.yaml文件
def clear_extract_yaml():
    try:
        with open(get_object_path() + "/configs/extract.yaml", encoding="utf-8", mode='w') as f:
            f.truncate()
    except Exception as e:
        logs.error(f'清除extract.yaml失败, 失败原因: {e}')


if __name__ == '__main__':
    # write_extract_file({"gaga": "23"})
    # clear_extract_file()
    test = read_config_file('api_keys', 'hamc_secret')
    print(test)
    # res = read_extract_yaml('test', 'testcase')
    # print(res)
    # clear_extract_yaml()
